﻿
using System.IO;
using System.Web.UI.WebControls;

namespace Portal.GUI.Advs.AdManager
{
	using System;
	using System.Data;
	using System.Web;
	using Portal.Core.DAL;

	/// <summary>
	///		Summary description for AdArrange.
	/// </summary>
	public partial class AdArrange : Portal.API.Module
	{
		protected string sPicture;

		/// <summary>
		/// Lưu File và trả lại tên file
		/// </summary>
		/// <param name="pFile">File được gửi đến</param>
		/// <param name="sPath">Đường dẫn thư mục sẽ lưu file</param>
		/// <returns></returns>
		private string FileName(HttpPostedFile pFile,string sPath)
		{
			string[] _arrFile ;
			string _sFile="Picture";
			char delimit='\\';
			try
			{
				if(pFile!=null)
				{
					_arrFile=pFile.FileName.Split(delimit);
					_sFile=_arrFile[_arrFile.GetUpperBound(0)].ToString();
					pFile.SaveAs(sPath + _sFile);
				}
			}	
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			return _sFile;

		}


		/// <summary>
		/// Thủ tục nạp vị trí của quảng cáo 
		/// </summary>
		private void LoadPositionList()
		{
			if (lstTabs.SelectedItem != null)
			{
				DataTable _dtbAvaiablePosition = null;
				using (MainDB _objDB = new MainDB())
				{
					_dtbAvaiablePosition = _objDB.SelectQuery("select distinct Position From ADV_PlaceHolder Where TabRef = '" + lstTabs.SelectedValue + "'");
				}

				if (_dtbAvaiablePosition != null)
				{
					// Đặt các giá trị vào Radiolist
					lstPosi.DataSource = _dtbAvaiablePosition;
					lstPosi.DataValueField = "Position";
					lstPosi.DataTextField = "Position";
					lstPosi.DataBind();
					lstPosi.SelectedIndex =0;
				}
			}

		}
		protected void Page_Load(object sender, System.EventArgs e)
		{	
			// Put user code to initialize the page here

			if (!Page.IsClientScriptBlockRegistered("PopCalendar"))
			{
				Page.RegisterClientScriptBlock("PopCalendar", "<SCRIPT language=\"JavaScript\" src=\"Scripts/Calendar/popcalendar.js\" type=\"text/Javascript\"></SCRIPT>");
			}

			if( !IsPostBack)
			{
				imgStartDate.Attributes.Add("Onclick","popUpCalendar(" + imgStartDate.ClientID + ", " + txtStartDate.ClientID + ", 'mm/dd/yyyy');" );
				imgEndDate.Attributes.Add("Onclick","popUpCalendar(" + imgEndDate.ClientID + ", " + txtEndDate.ClientID + ", 'mm/dd/yyyy')");
				LoadImage();
				LoadCategory();
				LoadPositionList();
				LoadADV_PHolder();
				if(lstImgManage.Items.Count >0)
				{
					ViewLevel();
					txtLevel.ReadOnly =false;
					cmdLevel.Enabled =true;
				}
				else 
				{
					txtLevel.ReadOnly =true ;
					cmdLevel.Enabled =false;
				}
				try 
				{
					using(MainDB _objMainDB= new MainDB())
					{
						ADVRow _objADV= new ADVRow();
						_objADV= _objMainDB.ADVCollection.GetByPrimaryKey(Convert.ToInt32(lstImg.SelectedValue));
						txtDescription.Text=_objADV.Description;
						txtStartDate.Text=_objADV.StartDate.ToShortDateString();
						txtEndDate.Text=_objADV.EndDate.ToShortDateString();
						txtLink.Text =_objADV.HyperLink;
						modeID.Value=_objADV.ADV_ID.ToString();
						sPicture= _objADV.Object.ToString();
						Page.DataBind();
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
			this.lstTabs.SelectedIndexChanged += new EventHandler(lstTabs_SelectedIndexChanged);
		}
		#endregion

		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void LoadADV_PHolder()
		{
			string sSelect ;
			string sWhere;
			string sFrom ;
			DataTable _objTbADV_PHolder;
			
			sSelect=" SELECT A.[OBJECT],A.ADV_ID ";
			sFrom ="From ADV  A,ADV_PlaceHolder  PH";
			sWhere =" WHERE PH.TabRef='" + lstTabs.SelectedValue.ToString() + "' AND PH.[position]='" + lstPosi.SelectedValue.ToString() + "' AND ";
			sWhere = sWhere + "A.ADV_ID=PH.ADV_ID  Order by PH.ADV_Order asc";
			sSelect=sSelect +sFrom + sWhere ;

			try 
			{
				using ( MainDB _objMainDB =new MainDB ())
				{
					_objTbADV_PHolder=_objMainDB.SelectQuery(sSelect);
					lstImgManage.DataSource=_objTbADV_PHolder;
					lstImgManage.DataBind();
					if(lstImgManage.Items.Count>0) lstImgManage.SelectedIndex=0;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		private void LoadCategory()
		{
			PortalDefinition _objPortal = PortalDefinition.Load();
			foreach(PortalDefinition.Tab _objTab in _objPortal.tabs)
			{
				ShowTabItem(_objTab, lstTabs);
			}
		}

		private void ShowTabItem(PortalDefinition.Tab _objTab, System.Web.UI.WebControls.DropDownList _ddrTabsList)
		{
			ListItem _objNewTab = new ListItem((_objTab.parent == null ? "" : "----") + _objTab.title, _objTab.reference);
			_ddrTabsList.Items.Add(_objNewTab);

			foreach(PortalDefinition.Tab _objSubTab in _objTab.tabs)
			{
				ShowTabItem(_objSubTab, _ddrTabsList);
			}
		}

		private  void LoadImage()
		{
			DataTable _objADV;
			try
			{
				using(MainDB _objMainDB =new MainDB())
				{	
					string[] _arrListFields =_objMainDB.ADVCollection.MakeListFields("OBJECT","ADV_ID");
					_objADV = _objMainDB.ADVCollection.GetAsDataTable(_arrListFields,"","");
					lstImg.DataSource =_objADV;	
					lstImg.DataBind();
					if (lstImg.Items.Count >0) lstImg.SelectedIndex =0;
				}
			}
			catch (Exception ex)
			{
				Console.Write(ex.Message);
			}
			lstImg.DataBind();
			
		}

		protected void cmdCrtImg_Click(object sender, System.EventArgs e)
		{
			string sPath= Request.PhysicalApplicationPath + "Images/AdImages/";
			if(mode.Value.ToUpper()!="NEW") //Kiểm tra xem đã chọn tạo mới chưa 
			{

			  mode.Value="NEW";
				cmdCrtImg.Text="Kết thúc tạo mới";  
				cmdCrtImg.CausesValidation =true;
				cmdCancelImg.Text= "Dừng tạo mới";
				cmdCancelImg.Enabled =true;
				cmdUpdImg.Enabled =false;	
				lstImg.Enabled =false ;
				txtLink.ReadOnly =false;
				txtDescription.ReadOnly =false;
				txtLink.Text="";
				txtDescription.Text="";
				cmdCrtImg.CausesValidation=true;
				//Response.Write("Mode=" + mode.Value);
			}
			else
			{
				mode.Value="";
				cmdCrtImg.Text="Tạo mơi quảng cáo";   	
				cmdCancelImg.Text= "Dừng";	
				cmdCancelImg.Enabled =false;
				lstImg.Enabled =true;
				txtLink.ReadOnly =true;
				txtDescription.ReadOnly =true;
				cmdCrtImg.CausesValidation =false;
				//Response.Write("Mode=" + mode.Value);
				//Cập nhật vào CSDL
				try 
				{
					ADVRow _objADVrow= new ADVRow();
					_objADVrow.Object= FileName(FileImg.PostedFile ,sPath);
					_objADVrow.HyperLink=txtLink.Text.Replace("'","''");
					_objADVrow.StartDate =Convert.ToDateTime(txtStartDate.Text);
					_objADVrow.EndDate=Convert.ToDateTime(txtEndDate.Text);
					_objADVrow.Description=txtDescription.Text.Replace("'","''");
					_objADVrow.Clicked =0;

					using( MainDB _objMainDB=new MainDB())	
					{
						_objMainDB.ADVCollection.Insert(_objADVrow);
					}
				}
				catch(Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				LoadImage();
			}			
		}

		protected void cmdDelImg_Click(object sender, System.EventArgs e)
		{
			ADVRow _objSelectedAdv = null;
			using(MainDB _objMainDB=new MainDB())
			{
				try
				{
					_objSelectedAdv = _objMainDB.ADVCollection.GetByPrimaryKey(Convert.ToInt32(lstImg.SelectedValue));
					_objMainDB.ADV_PlaceHolderCollection.DeleteByADV_ID(Convert.ToInt32(lstImg.SelectedValue));
					_objMainDB.ADVCollection.Delete("ADV_ID=" + lstImg.SelectedValue.ToString());
				}
				catch(Exception ex)
				{
					Console.WriteLine(ex.Message);
				}

			}

			if (_objSelectedAdv != null)
			{
				File.Delete(Server.MapPath("~/") + "/" + "Images/AdImages/" + _objSelectedAdv.Object);
			}
			LoadImage();

		}

		protected void cmdUpdImg_Click(object sender, System.EventArgs e)
		{
			if(mode.Value.ToUpper()!="EDIT") //Khởi tạo các giá trị cho quá trình Sửa 
			{    
				mode.Value="EDIT";
				modeID.Value=lstImg.SelectedValue.ToString();
				cmdUpdImg.Text="Chấp nhận cập nhập";
				cmdCancelImg.Text="Dừng cập nhật";
				cmdCancelImg.Enabled =true;	
				cmdCrtImg.Enabled =false ;
				lstImg.Enabled =false;
				txtLink.ReadOnly =false;
				txtDescription.ReadOnly =false;
				cmdUpdImg.CausesValidation =true;
				

			}
			else   //Thi hành quá trình Sửa 
			{
				mode.Value="";
				cmdUpdImg.Text="Cập nhâp";
				cmdCancelImg.Text="Dừng";
				cmdUpdImg.CausesValidation =false;
				cmdCancelImg.Enabled =false;
				cmdCrtImg.Enabled =true; ;
				txtLink.ReadOnly =true;
				txtDescription.ReadOnly =true;
				lstImg.Enabled =true;
				string sPath;
				sPath=Request.PhysicalApplicationPath + "Images/AdImages/";
				//Response.Write("Mode=" + mode.Value);
				using( MainDB _objMainDB= new MainDB())
				{
					 ADVRow _objADVrow =_objMainDB.ADVCollection.GetByPrimaryKey(Convert.ToInt32(modeID.Value));
					 _objADVrow.StartDate =Convert.ToDateTime(txtStartDate.Text) ;
					 _objADVrow.EndDate=Convert.ToDateTime(txtEndDate.Text);
					 _objADVrow.Description =txtDescription.Text.Replace("'","''");
					 _objADVrow.HyperLink =txtLink.Text.Replace("'","''");
					 if(FileImg.Value !="")
						_objADVrow.Object=FileName(FileImg.PostedFile ,sPath);
					 _objMainDB.ADVCollection.Update(_objADVrow);
				}
			}
		}

		protected void lstImg_SelectedIndexChanged(object sender, System.EventArgs e)
		{   
			using(MainDB _objMainDB= new MainDB())
			{
				ADVRow _objADV= new ADVRow();
				_objADV= _objMainDB.ADVCollection.GetByPrimaryKey(Convert.ToInt32(lstImg.SelectedValue));
				txtDescription.Text=_objADV.Description ;
				txtStartDate.Text=_objADV.StartDate.ToShortDateString();
				txtEndDate.Text=_objADV.EndDate.ToShortDateString() ;
				txtLink.Text =_objADV.HyperLink ;
				sPicture= _objADV.Object.ToString();
				Page.DataBind();
				modeID.Value=_objADV.ADV_ID.ToString() ;
			}
		}

		protected void cmdCancelImg_Click(object sender, System.EventArgs e)
		{
			mode.Value="";
			cmdCancelImg.Text="Dừng";
			cmdUpdImg.Text="Cập nhât";
			cmdCrtImg.Text="Tạo mới quảng cáo";
			cmdCrtImg.Enabled =true;
			cmdCancelImg.Enabled =false ;
			cmdUpdImg.Enabled =true;
			lstImg.Enabled =true;
			txtLink.ReadOnly =true;
			txtDescription.ReadOnly =true;
			cmdCrtImg.CausesValidation =false;
			cmdUpdImg.CausesValidation =false;					
		}

		protected void lstImgManage_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(lstImgManage.Items.Count >0)
			{
				ViewLevel();
				txtLevel.ReadOnly =false;
				cmdLevel.Enabled =true;
			}
			else 
			{
				txtLevel.ReadOnly =true ;
				cmdLevel.Enabled =false;
			}	

			using(MainDB _objMainDB= new MainDB())
			{
				ADVRow _objADV= new ADVRow();
				
				_objADV= _objMainDB.ADVCollection.GetByPrimaryKey(Convert.ToInt32(lstImgManage.SelectedValue));
				lblClicked.Text =_objADV.Clicked.ToString()  ;
				txtDescription.Text=_objADV.Description ;
				txtStartDate.Text=_objADV.StartDate.ToShortDateString();
				txtEndDate.Text=_objADV.EndDate.ToShortDateString() ;
				txtLink.Text =_objADV.HyperLink ;
				sPicture= _objADV.Object.ToString();
				modeID.Value=_objADV.ADV_ID.ToString() ;
				Page.DataBind();
			}
		}

		protected void cmdCrtADV_Click(object sender, System.EventArgs e)
		{
			Int32 intLevel=0;
			Int32 intOrder=1;
			DataTable _objTbOrder;
			string sWhere="";
			string[] sSelect;
			using( MainDB _objMainDB= new MainDB())
			{
				try 
				{
					sWhere="TabRef='" + lstTabs.SelectedValue.ToString() +"' AND [Position]='" + lstPosi.SelectedValue.ToString() + "'";
					sSelect=_objMainDB.ADV_PlaceHolderCollection.MakeListFields("ADV_ORDER");
					_objTbOrder= _objMainDB.ADV_PlaceHolderCollection.GetAsDataTable(sSelect,sWhere,"ADV_ORDER Desc") ;
					if(_objTbOrder.Rows.Count >0)
						intOrder=Convert.ToInt32(_objTbOrder.Rows[0]["ADV_ORDER"].ToString()) +1;
					ADV_PlaceHolderRow _objADV_PHolder = new ADV_PlaceHolderRow();
					_objADV_PHolder.TabRef = lstTabs.SelectedValue;
					_objADV_PHolder.Position = txtNewPosition.Text.Trim().Replace(" ", "") != "" ? txtNewPosition.Text.Trim().Replace(" ", "").ToUpper() : lstPosi.SelectedValue;
					_objADV_PHolder.ADV_ID = Convert.ToInt32(lstImg.SelectedValue);
					_objADV_PHolder.Adv_Level = intLevel;
					_objADV_PHolder.Adv_Order = intOrder;
					_objMainDB.ADV_PlaceHolderCollection.Insert(_objADV_PHolder);
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}

			
			LoadPositionList();
			LoadADV_PHolder();

		}

		protected void lstPosi_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			LoadADV_PHolder();
			if(lstImgManage.Items.Count >0)
			{
				ViewLevel();
				txtLevel.ReadOnly =false;
				cmdLevel.Enabled =true;
			}
			else 
			{
				txtLevel.ReadOnly =true ;
				cmdLevel.Enabled =false;
			}
		}

		protected void cmdDelADV_Click(object sender, System.EventArgs e)
		{
			string sWhere ;
			try 
			{
				sWhere="ADV_ID=" + lstImgManage.SelectedValue.ToString() + " AND TabRef='";
				sWhere += lstTabs.SelectedValue.ToString() + "' AND [Position]='";
				sWhere += lstPosi.SelectedValue + "'";
				using(MainDB _objMainDB= new MainDB())
				{	
					_objMainDB.ADV_PlaceHolderCollection.Delete(sWhere);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			LoadADV_PHolder();
			if(lstImgManage.Items.Count >0)
			{
				txtLevel.ReadOnly =true;
				cmdLevel.Enabled =true;
			}
			else 
			{
				txtLevel.ReadOnly =false ;
				cmdLevel.Enabled =false;
			}
			
		}

		protected void cmdLevel_Click(object sender, System.EventArgs e)
		{
			string sUpdate;
			string sWhere;
			
			Int32 intLevel=0;
			if(txtLevel.Text!="")
				   intLevel=Convert.ToInt32(txtLevel.Text);
				
			using(MainDB _objMainDB=new MainDB())
			{   
				sUpdate="Update ADV_PlaceHolder set ADV_Level=" + intLevel.ToString() ;
				sWhere=" Where ADV_ID=" + lstImgManage.SelectedValue.ToString() + " AND TabRef='" ;
				sWhere += lstTabs.SelectedValue.ToString() + "' AND [Position]='";
				sWhere += lstPosi.SelectedValue + "'" ;
				sUpdate=sUpdate + sWhere ;
			    _objMainDB.AnotherNonQuery(sUpdate);
			}
		}

		private void ViewLevel()
		{
			DataTable _objTbADV_PHolder;
			string sWHERE ;
			string sSelect;
			try 
			{
				using(MainDB _objMainDB=new MainDB())
				{
					sSelect="SELECT ADV_LEVEL FROM ADV_PlaceHolder "; 
					sWHERE=" WHERE  ";
					sWHERE += " ADV_ID=" + lstImgManage.SelectedValue.ToString() + " AND TabRef='" ;
					sWHERE += lstTabs.SelectedValue.ToString() + "' AND [Position]='" ;
					sWHERE += lstPosi.SelectedValue.ToString() + "'";
					sSelect=sSelect + sWHERE;
					_objTbADV_PHolder = _objMainDB.SelectQuery(sSelect);
					txtLevel.Text=_objTbADV_PHolder.Rows[0]["ADV_LEVEL"].ToString();
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		private void lstTabs_SelectedIndexChanged(object sender, EventArgs e)
		{	
			LoadPositionList();
			LoadADV_PHolder();
			if(lstImgManage.Items.Count >0)
			{
				ViewLevel();
				txtLevel.ReadOnly =false;
				cmdLevel.Enabled =true;
			}
			else 
			{
				txtLevel.ReadOnly =true ;
				cmdLevel.Enabled =false;
			}
		}
	}

}
